package com.gitee.feizns.dynamic.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 关于压缩包的工具类
 * @author feizns
 * @since 2019/5/8
 */
public abstract class Zips {

    /**
     * 压缩缓存区大小
     */
    private static final int BUFFER_SIZE = 5025;

    /**
     * 压缩成ZIP 方法2
     * @param files 需要压缩打包的文件列表
     * @param os 压缩文件输出流，一般是zip包的位置
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void write(List<File> files , OutputStream os) throws IOException {
        try ( ZipOutputStream zos = new ZipOutputStream(os) ) {
            for (File srcFile : files) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
        }
    }

}
